package mx.com.sinformex.simbel.pages.admin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import mx.com.sinformex.simbel.components.GenericSelectModel;
import mx.com.sinformex.simbel.db.eos.DataSource;
import mx.com.sinformex.simbel.db.eos.Report;
import mx.com.sinformex.simbel.db.eos.ReportParam;
import mx.com.sinformex.simbel.pages.BasicPage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tapestry5.PrimaryKeyEncoder;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.upload.services.UploadedFile;

/**
 * @author Oscar Ivan Hernandez Ventura [ oscar at sinformex dot com dot mx]
 *
 * @version $ Id : Reports.java , v 1.0 11/05/2009 angellore $
 */
public class Reports extends BasicPage {

	@Property
	@Persist
	private Report report;
	
	private final Log log = LogFactory.getLog(getClass());

    private GenericSelectModel<DataSource> dsModel;
    @Persist
    @Property
    private DataSource ds;
    @Inject
    private PropertyAccess _access;    
    @Property
    private ReportParam param;
    @Property
    private UploadedFile jasperFile;

    
	public List<Report> getReports() {
		return getAdminDataAccess().fetchReports();
	}
	
	void onActionFromCreate() {
		getSession().setListing(false);
		getSession().setEditing(false);
		getSession().setInserting(true);
		report = new Report();
	}
	
	void onActionFromEdit(Integer id) {
		getSession().setListing(false);
		getSession().setInserting(false);
		getSession().setEditing(true);
		report = getAdminDataAccess().getReport(id);
		ds = report.getDatasource();
	}
	
	void onValidate() {
		if(getSession().isInserting()) {
			Object o = getAdminDataAccess().getReport(report.getReportId());
			if(o != null) {
				log.error(String.format("The report %s already exist.", report.getReportId()));
				setError(String.format("The report %s already exist.", report.getReportId()));
			}
		}
		if(ds == null) {
			log.error("The ds is null.");
			setError("The Datasources is needed.");
		}
	}
	
	void onSuccess() {
		if(getError() != null) {
			return;
		}
		if(!getSession().isListing() || report != null) {
			
			if(jasperFile != null) {
				log.info(String.format("Uploading file %s", jasperFile.getFilePath()));
				File copied = new File("/usr/local/jboss-bprepaid-4.2.3.GA/server/default/jrxml-templates/" + jasperFile.getFileName());//TODO esto debe cambiar a algo configurable
				jasperFile.write(copied);
				report.setJasperReportFileName(jasperFile.getFileName());
				jasperFile = null;
				copied = null;
			}
			
			report.setDatasource(ds);
			report.setDatasourceName(ds.getName());
			if(getSession().isEditing()) {
				getAdminDataAccess().updateReport(report);
			} else if(getSession().isInserting()) {
				getAdminDataAccess().saveReport(report);
			}
			report = null;
			getSession().setListing(true);
			getSession().setEditing(false);
			getSession().setInserting(false);
		}
	}

	public GenericSelectModel<DataSource> getDsModel() {
		if(dsModel == null) {
			dsModel = new GenericSelectModel<DataSource>(getAdminDataAccess().fetchDatasources(),DataSource.class,"name","name",_access);
		}
		return dsModel;
	}

	@SuppressWarnings("deprecation")
	public PrimaryKeyEncoder<Integer, ReportParam> getParamsEncoder() {
		return new PrimaryKeyEncoder<Integer, ReportParam>() {
			public Integer toKey(ReportParam value) {
				return value.getReportParamId();
			}

			public void prepareForKeys(List<Integer> keys) {
			}

			public ReportParam toValue(Integer key) {
				return (ReportParam) report.getParam(key);
			}

			public Class<Integer> getKeyType() {
				return Integer.class;
			}
		};
	}	
	
	Object onAddRowFromParams() {
		ReportParam param = new ReportParam();
		param.setDataType("");
		param.setDefaultValue("Default Value");
		param.setDescription("Description");
		param.setField("Field Name");
		param.setName("Name");
		param.setReportId(report.getReportId());
		param.setNewItem(true);
		param.setRequired(false);
		param.setStaticParam(false);
		
		report.addToParams(param);
		
		getAdminDataAccess().addParamToReport(report, param);
		report = getAdminDataAccess().getReport(report.getReportId());
		
		return param;
	}

	void onRemoveRowFromParams(ReportParam param) {
		getAdminDataAccess().deleteParamFromReport(report, param);
		report = getAdminDataAccess().getReport(report.getReportId());
	}
	

}
